
// 路由守卫-页面刷新时-获取token、菜单
import router from '../router'
import store from '../store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/cookies'
import defaultSettings from '../settings'

const title = defaultSettings.title || 'Admin'
document.title = title

NProgress.configure({ showSpinner: false })
const whiteList = ['/login', '/agreement', '/forget']

const initMenuByRole = async () => {
  const hasToken = getToken()
  if (!hasToken) return

  // const fetchMenuCount = store.getters.fetchMenu

  // if (fetchMenuCount >= 1) return

  // get user info
  // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
  await store.dispatch('user/getInfo')
  // generate accessible routes map based on roles
  const { routes } = await store.dispatch('permission/generateRoutes')
  // dynamically add accessible routes
  router.addRoutes(routes)
}

router.beforeEach(async (to, from, next) => {
  // 当前为静态路由模式
  // 不校验token、菜单
  // 直接进入
  if (defaultSettings.routerType === 'static') {
    NProgress.start()
    next()
    NProgress.done()
    return
  }
  // set page title
  // document.title = `${to.meta.title}-${title}`

  /**
   * @description 判断用户是否已经登录
   */
  const hasToken = getToken()

  /**
   * @description 优先判断白名单
   */
  if (whiteList.indexOf(to.path) !== -1) {
    if (hasToken && to.path === '/login') {
      /**
       * @description 判断是首次登陆则修改密码
       */
      next({ path: '/' })
      NProgress.done()
      return
    }
    await initMenuByRole()
    next()
    NProgress.done()
    return
  }
  // 判断是否有token
  if (hasToken) {
    // 判断是否已经登录
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      // 判断是否已经获取菜单
      // 避免重复获取菜单
      const fetchMenuCount = store.getters.fetchMenu
      if (fetchMenuCount >= 1) {
        next()
      } else {
        try {
          await initMenuByRole()
          // hack method to ensure that addRoutes is complete
          next({ ...to, replace: true })
        } catch (error) {
          // token失效
          // remove token and go to login page to re-login
          // re-login by status deal
          await store.dispatch('user/resetToken')
          // 在menu菜单获取为null时，error中会存在path属性
          next({
            path: error.fullPath ? error.fullPath : `/login?redirect=${to.fullPath}`,
            replace: true
          })
          NProgress.done()
        }
      }
    }
    return
  } else {
    await store.dispatch('user/resetToken')
    next({ path: `/login?redirect=${to.fullPath}`, replace: true })
    NProgress.done()
  }
})

router.afterEach(() => {
  NProgress.done()
})
